﻿using Microsoft.Office.Interop.Excel;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web.UI;

namespace Common.Net
{
    public class OfficeHelper
    {
        public static bool ExcelSaveAsXlsx(string sourcePath, string targetPath)
        {
            bool flag;
            bool isError = false;
            object missing = Type.Missing;
            Microsoft.Office.Interop.Excel.ApplicationClass class2 = null;
            Workbook workbook = null;
            try
            {
                class2 = new Microsoft.Office.Interop.Excel.ApplicationClass();
                object filename = targetPath;
                XlFixedFormatType xlTypePDF = XlFixedFormatType.xlTypePDF;
                workbook = class2.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                workbook.SaveAs(targetPath, XlFileFormat.xlOpenXMLWorkbook, missing, missing, false, false, XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
                flag = true;
            }
            catch (Exception ex)
            {
                flag = false;
                isError = true;
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close(false, missing, missing);
                    workbook = null;
                }
                if (class2 != null)
                {
                    class2.Quit();
                    class2 = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                if (isError)
                {
                    foreach (Process process in Process.GetProcessesByName("Excel"))
                    {
                        process.Kill();
                    }
                }
            }
            return flag;
        }
    }
}
